class SuperTask {
  constructor(paralleCount = 2) {
    this.paralleCount = paralleCount;
    this.tasks = [];
    this.runningCount = 0;
  }
  add(task) {
    return new Promise((resolve, reject) => {
      this.tasks.push({ task, resolve, reject });
      this._run();
    });
  }
  _run() {
    while (this.runningCount < this.paralleCount && this.tasks.length) {
      const { task, resolve, reject } = this.tasks.shift();
      this.runningCount++;
      Promise.resolve(task())
        .then(resolve, reject)
        .finally(() => {
          this.runningCount--;
          this._run();
        });
    }
  }
}

const superTask = new SuperTask();
function timeout(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}
function addTask(time, name) {
  superTask
    .add(() => timeout(time))
    .then(() => {
      console.log(`任务${name}完成`);
    });
}
addTask(10000, 1);
addTask(5000, 2);
addTask(30000, 3);
addTask(40000, 4);
addTask(50000, 5);
addTask(60000, 6);

// console.log("1");
// new Promise((resolve, reject) => {
//   console.log("2");
//   resolve();
// })
//   .then((resolve, reject) => {
//     setTimeout(() => {
//       console.log("4");
//       resolve;
//     }, 100);
//   })
//   .then((resolve, reject) => {
//     console.log("5");
//   })
//   .finally(() => {
//     console.log("finally");
//   });
// console.log("3");
